<?php

namespace app\home\controller;
use app\api\model\merchant\MerchantModel;
use app\home\model\order as OrderModel;
use app\Request;
use think\Cache;
use think\facade\Session;
use ulit\thirdPayment\AuthPay;
use yzh52521\EasyHttp\Http;
use yzh52521\EasyHttp\RequestException;
use yzh52521\EasyHttp\Response;

class Order extends MeberBase
{

    public function list(){




        $where[]=['merchant_id','=',session('member_id')];

        $total_money=OrderModel\Order::where($where)->where(['status'=>1])->sum('amount');
        $actual_amount=OrderModel\Order::where($where)->where(['status'=>1])->sum('actual_amount');
        $commission=OrderModel\Order::where($where)->where(['status'=>1])->sum('commission');
        return view('order/list',['total_money'=>$total_money,'actual_amount'=>$actual_amount,'commission'=>$commission]);

    }

    public function ajaxList(): \think\response\Json
    {


        $list= OrderModel\Order::list();

        return $this->result($list);
    }
    public function findOrder(Request $request)
    {
        if ($request->isPost() && $request->isAjax()) {
            $order_sn=$request->param('order_sn');
            $result=AuthPay::getInstance()->query($order_sn);

            $res=json_decode($result,true);


            if($res['result']['orderStatus']==4){
                $msg=$res['result']['remark'];
            }else{
                $res['message']?$msg=$res['message']:$msg='数据异常';
            }

            return $this->result(['code'=>200,'msg'=>$msg,'data'=>$res['result']]);
        }
        return $this->error();

    }

    public function payOrder(Request $request)
    {


        if($request->isPost() && $request->isAjax()){
            $member_id=Session::get('member_id');

            $MemberKeyInfo= MerchantModel::where(['id'=>$member_id])->find(); //获取商户密钥
            $out_trade_id=getRandOrderSn('test');
            $signs=[
                'appid'=>$MemberKeyInfo->appid,
                'out_trade_id'=>$out_trade_id,
                'amount'=>$request->param('amount'),
                'secret'=>$MemberKeyInfo->secret,
                'notify_url'=>$request->param('notify_url'),
            ];

            $sign=makeApiSign($signs,$MemberKeyInfo->key);
            $data=$request->param('');
            $data['sign']=$sign;
            $data['appid']=$MemberKeyInfo->appid;
            $data['secret']=$MemberKeyInfo->secret;
            $data['out_trade_id']=$out_trade_id;
           // $result=httpRequest('http://test.com//api.php/Payment/pay','POST',$data,[]);
     
           $promise = Http::post($request->domain().'/api.php/Payment/pay',$data);
            
    

            return  $this->result(json_decode($promise->body(),true));
        }


        return view('order/pay');
    }
}